<template>
  <el-dialog
    v-model="createVisible"
    :title="operation == 'create' ? '添加物流公司' : '编辑物流公司'"
    @before-ok="createOk"
    @close="close(createRef)"
    top="100px"
    width="700px"
  >
    <div style="width: 600px">
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="130px"
        size="default"
        v-loading="initLoading"
      >
        <el-form-item label="物流公司名称：" prop="company_name">
          <el-input
            v-model="createForm.company_name"
            placeholder="请输入物流公司名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="开启电子面单：" prop="is_electron_order">
          <el-radio-group v-model="createForm.is_electron_order">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
          </el-radio-group>
          <help>该面单控制优先聚合物流平台，直接提交至物流平台</help>
        </el-form-item>
        <template v-if="createForm.is_electron_order == 1">
            <el-form-item>
                <el-button plain type="primary" size="small" @click="addSetting">添加配置项</el-button>
                <div class="setting-box">
                    <template v-for="(item,index) in settingData" :key="index">
                        <div class="setting-item">
                            <div class="setting-item-top">
                                第 {{index + 1}} 项配置
                            </div>
                            <div class="setting-item-del" @click="delSetting(index)">删除</div>
                            <div class="setting-item-main">
                                <div class="setting-item-left">
                                    <el-input
                                        size="small"
                                        v-model="item.key"
                                        placeholder="请输入配置标识"
                                    ></el-input>
                                </div>
                                <div  class="setting-item-right">
                                    <el-input
                                        size="small"
                                        v-model="item.value"
                                        placeholder="请输入配置值"
                                    ></el-input>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </el-form-item>
        </template>


        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="createForm.status">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input-number v-model="createForm.sort" :min="0" :max="10000" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="flex center">
        <el-button @click="createVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          :disabled="btnLoading"
          @click="createOk(createRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
  
  <script lang="ts">
export default {
    name: "storeExpressCompanyCreate",
    components: { help }
};
</script>
  <script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive } from "vue";
import type { FormInstance } from "element-plus";
import {
  createExpressCompany,
  updateExpressCompany,
  getExpressCompanyDetail,
} from "@/api/store/express_company";
import type { Result, ResultError } from "@/types";
import { help } from "@/components";

const {
  proxy,
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const createVisible = ref<boolean>(false);

const operation = ref<string>("create");

const operationId = ref<number>(0);

const createRef = ref<typeof FormInstance>();

const btnLoading = ref<boolean>(false);

const parentTree = ref<any>([]);

const initLoading = ref<boolean>(true);

const toInit = () => {
  if (!operationId.value) {
    initLoading.value = false;
    return;
  }
  getExpressCompanyDetail({ id: operationId.value })
    .then((res: Result) => {
      createForm.value.company_name = res.data.company_name;
      createForm.value.sort = res.data.sort;
      createForm.value.status = res.data.status.value;
      createForm.value.setting = $utils.toArray(res.data.setting)
      settingData.value = $utils.toArray(res.data.setting)
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const createForm = ref({
  company_name: "",
  is_electron_order:1,
  sort: 0,
  status: 1,
  setting:[]
});
const createRules: any = reactive({
  company_name: [{ required: true, message: "物流公司名称不能为空！" }],
});


const settingData = ref<any>([])
    
const addSetting = () => {
    settingData.value.push({
        key:'',
        value:''
    })
}

const delSetting = (idx:number) => {
    settingData.value.splice(idx,1)
}

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      if (btnLoading.value) {
        return;
      }
      if(createForm.value.is_electron_order){
        createForm.value.setting = settingData.value
      }
      btnLoading.value = true;
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createExpressCompany(createForm.value);
      } else {
        operationApi = updateExpressCompany(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const open = (id: number = 0) => {
  initLoading.value = true;
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
};

defineExpose({ open });
</script>

<style scoped>
.setting-box{
    width: 100%;
    font-size: 12px;
    max-height: 240px;
    overflow-y: scroll;
}
.setting-item{
    padding: 10px;
    margin-top: 10px;
    border:1px solid #f0f0f0;
    position: relative;
    border-radius: var(--base-radius);
    position: relative;
}
.setting-item-top{
    line-height: 16px;
}
.setting-item-main{
    display: flex;
    justify-content: space-between;
}
.setting-item-left,.setting-item-right{
    width: 45%;
}
.setting-item-del{
    position: absolute;
    top: 0;
    right: 10px;
    cursor: pointer;
    user-select: none;
}
.setting-item-del:hover{
    color: var(--base-default);
}
</style>